import React from "react";
import { toJS } from "mobx";
import { DragLayer } from 'react-dnd'
import { Icon } from "antd";
import { dndTypes } from "../../../../constants";

const layerStyles = {
    position: 'fixed',
    pointerEvents: 'none',
    zIndex: 100,
    left: 0,
    top: 0,
    width: '100%',
    height: '100%',
}

@DragLayer(monitor => ({
    item: monitor.getItem(),
    itemType: monitor.getItemType(),
    initialOffset: monitor.getInitialSourceClientOffset(),
    currentOffset: monitor.getSourceClientOffset(),
    isDragging: monitor.isDragging(),
}))
export default class DragPreview extends React.Component {
    getItemStyles() {
        const { initialOffset, currentOffset } = this.props

        if (!initialOffset || !currentOffset) {
            return {
                display: 'none',
            }
        }

        let { x, y } = currentOffset;

        const transform = `translate(${x}px, ${y}px)`;

        return {
            transform,
            WebkitTransform: transform,
        }
    }

    renderItem() {
        const { item, itemType } = this.props;
        const { node } = item;

        switch (itemType) {
            case dndTypes.JOINED_TABLE:
                return this.renderNode(node, true);
            case dndTypes.TABLE: 
                return (
                    <div className='edc-ds-tree-item'>
                        <h6>{node.name || node.text}</h6>
                    </div>
                );
            default:
                return null;
        }
    }

    renderNode(node, isroot) {
        const fields = toJS(node.relatedFields) || [];
        const len = fields.filter(f => f[0] && f[1]).length;

        return (
            <div className='edc-ds-tree-box' key={node.id}>
                <div className='edc-ds-tree-item'>
                    <h6>{node.name || node.text}</h6>
                    { isroot ? null :
                        <span className={`edc-ds-tree-opt ${!len ? 'err' : ''}`}>
                            {len ? <b>{len}</b> : <Icon type='plus' />}
                            <Icon type='edit' />
                        </span>
                    }
                </div>
                <div className='edc-ds-tree-wrap'>
                    {node.children.map(n => this.renderNode(n))}
                </div>
            </div>
        );
    }

    render() {
        const { isDragging } = this.props;
        
        if (!isDragging) {
            return null;
        }

        return (
            <div style={layerStyles}>
                <div style={this.getItemStyles()}>{this.renderItem()}</div>
            </div>
        );
    }
}